<?php

namespace app\shopapi\model\pay;


use app\admin\model\User;
use app\common\library\Sms as Smslib;
use app\shopapi\model\Shop;
use app\shopapi\model\ShopBills;
use fast\Http;



//商户进件
class ShopInfeed1
{

    public $agent_no =  '84822596';
    public $secret_key = '3fb101f9512b47de0bf6a36ef524b518';

    //商户入网
    public function apply($shop_id)
    {
        $shop_info = Shop::get($shop_id);

        $api = "https://test.esw235.com/unipay/enter/register";

        $request = \think\Request::instance();
        $notify_url = $request->root(true) . '/shopapi/shop/back';

        $merchant_img_corporate_id_card_front = $this->upload($shop_info['front_id_card_img']);

        $merchant_img_corporate_id_card_obverse = $this->upload($shop_info['reverse_id_card_img']);

        $merchant_img_door_shot = $this->upload($shop_info['banner_img']);

        $merchant_img_shop_interior = $this->upload($shop_info['interior_img']);
        $data = [
            //'merchant_type'=>$merchant_type,//商户类型 1:个体 2:企业 3:小微
            'store_name'=>$shop_info['shop_name'],//商户简称
            'mcc_code'=>'1',//商户MCC编码
            'store_contacts'=>$shop_info['realname'],//商户联系人（建议和法人一致）
            'store_tel'=>$shop_info['mobile'],//联系人手机号码（签约手机号）
            'province_code'=>$shop_info['province_code'],//商户所在省 地区码
            'city_code'=>$shop_info['city_code'],//商户所在市 地区码
            'area_code'=>$shop_info['area_code'],//商户所在区县 地区码
            'store_address'=>$shop_info['address'],//商户详细地址
            /*'bse_lice_nm'=>'',//商户名称（个体和企业必须为营业执照名称，小微格式为：商户_姓名）
            'bus_lic_no'=>$shop_info['business_license_num'],//营业执照号（个体和企业必传）
            'bus_lic_address'=>'',//营业执地址（个体和企业必传）
            'bus_start_dt'=>'',//营业执照开始日期（个体和企业必传）
            'bus_exp_dt'=>'',//营业执照结束日期（个体和企业必传）（长期有效9999-12-31）
            'merchant_img_electronic_business_license'=>'',//营业执照片（个体和企业必传）*/
            'crp_nm'=>$shop_info['id_card_name'],//法人姓名
            'crp_id'=>$shop_info['id_card_num'],//法人身份证号
            'crp_mobile'=>$shop_info['legal_person_phone'],//法人手机号
            'crp_start_dt'=>$shop_info['id_card_start_time'],//法人身份证有效期开始日期
            'crp_exp_dt'=>$shop_info['id_card_end_time'],//法人身份证有效期结束日期（长期有效9999-12-31）
            'merchant_img_corporate_id_card_front'=>$merchant_img_corporate_id_card_front,//法人身份证正面
            'merchant_img_corporate_id_card_obverse'=>$merchant_img_corporate_id_card_obverse,//法人身份证反面
            //'settlement_account_type'=>'',//结算账户类型 00:对公账户 01:法人账户02：被授权人账户 (小微仅支持法人账户)
            'settlement_bank'=>$shop_info['bank_name'],//开户行
            'settlement_open_subbank'=>$shop_info['bank'],//开户行支行
            'settlement_bank_code'=>$shop_info['bank_code'],//联行号
            'settlement_account_name'=>$shop_info['id_card_name'],//账号名
            'settlement_card_number'=>$shop_info['bank_num'],//结算卡号
            'settlement_bank_tel'=>$shop_info['legal_person_phone'],//银行预留手机号
            //'merchant_img_permit_for_bank_account'=>'',//开户许可证（对公必传）
            'merchant_img_door_shot'=>$merchant_img_door_shot,//门头照
            'merchant_img_shop_interior'=>$merchant_img_shop_interior,//店内景照
            'notify_url'=>$notify_url,
            'ledger_rate'=>100-$shop_info['commission_rate'],
            'rate'=>[
                'merchant_wxpay_d1_rate'=>'0.3',
                'merchant_alipay_d1_rate'=>'0.3',
                'merchant_unionscan_debit_d1_rate'=>'0.5',
                'merchant_unionscan2_debit_d1_rate'=>'0.3',
                'merchant_unionscan_debit_d1_cap'=>'20',
                'merchant_unionscan_credit_d1_rate'=>'0.6',
                'merchant_unionscan2_credit_d1_rate'=>'0.3'
            ],//费率信息
        ];
        if ($shop_info['subject_type']==2){
            //小微
            $data['settlement_account_type'] = 01;
            $data['bse_lice_nm'] = '商户_'.$shop_info['realname'];
        } else {
            $data['bse_lice_nm'] = $shop_info['business_license_name'];
            $data['bus_lic_no'] = $shop_info['business_license_num'];
            $data['bus_lic_address'] = $shop_info['business_license_address'];
            $data['bus_start_dt'] = $shop_info['business_license_start_dt'];
            $data['bus_exp_dt'] = $shop_info['business_license_end_dt'];
            $merchant_img_electronic_business_license = $this->upload($shop_info['business_license_img']);
            $data['merchant_img_electronic_business_license'] = $merchant_img_electronic_business_license;
        }

        //账户类型,1对公账户,0对私账户
        if ($shop_info['bank_type']==1){
            $data['settlement_account_type'] = '00';
            $data['merchant_img_permit_for_bank_account'] = $shop_info['merchant_img_permit_for_bank_account'];
        } else {
            $data['settlement_account_type'] = '01';
            $merchant_img_bank_card = $this->upload($shop_info['bank_card_img']);
            $data['merchant_img_bank_card'] = $merchant_img_bank_card;
            $merchant_img_bank_card_back = $this->upload($shop_info['bank_card_back_img']);
            $data['merchant_img_bank_card_back'] = $merchant_img_bank_card_back;
        }

        if ($shop_info['subject_type']==1){
            //个体工商户
            $data['merchant_type'] = 1;
        } elseif($shop_info['subject_type']==2){
            //个人 小微
            $data['merchant_type'] = 3;
        } else {
            //企业
            $data['merchant_type'] = 2;
        }

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($api,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            $shop_info->merchant_no = $result['data']['merchant_no'];
            $shop_info->secret_key = $result['data']['secret_key'];
            $shop_info->save();
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //电子合同
    public function contract($merchant_no)
    {
        $shop_info = Shop::get(['merchant_no'=>$merchant_no]);

        $api = "https://test.esw235.com/unipay/enter/eSign";

        $data = [
            'merchant_no'=>$merchant_no
        ];

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($api,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            //$request = \think\Request::instance();
            //$notify_url = $request->root(true) . '/shopapi/auth/contracturl';
            //保存合同链接然后发送短信
            $short_url = shortUrl($shop_info->contract_url);
            $shop_info->contract_url = $result['data']['resultUrl'];
            $shop_info->short_url = $short_url;
            $shop_info->save();
            $ret = Smslib::shopsend($shop_info['legal_person_phone'], null, 'sendcontract','shop',$short_url);

            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //聚合码
    public function qrcode($merchant_no)
    {
        $api = 'https://service.eswhyf.com/unipay/taxi/qrcode';

        $data = [
            'merchant_no'=>$merchant_no,
        ];

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($api,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){
            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //上传图片
    public function upload($file,$ext='')
    {
        $api = "https://test.esw235.com/unipay/merchant/upload";
        $imageData = file_get_contents($file);
        //dump(base64_encode($imageData));die;
        $data = [
            'file'=>base64_encode($imageData),
            'ext'=>$ext
        ];

        $pre_data = $this->signature($data);

        $res = Http::sendRequest($api,$pre_data);

        $result = json_decode($res['msg'],true);

        if ($result['code']==200){

            return $result['data'];
        } else {
            throw new \Exception($result['msg']);
        }
    }

    //商户入驻回调
    public function notify_url($data)
    {
        $merchant_no = isset($data['merchant_no'])?$data['merchant_no']:'';
        $merchant_name = isset($data['merchant_name'])?$data['merchant_name']:'';
        $audit_status = isset($data['audit_status'])?$data['audit_status']:'';
        $audit_msg = isset($data['audit_msg'])?$data['audit_msg']:'';
        $shop_info = Shop::get(['merchant_no'=>$merchant_no]);

        //审核状态 （0 待审核 1已审核 2驳回）
        if ($audit_status==1){
            $shop_info->audit_status=2;
        } elseif ($audit_status==2){
            $shop_info->audit_status=3;
            $shop_info->audit_msg=$audit_msg;
        }

        $res =  $shop_info->save();

        return $res;
    }


    //微信扫付款码支付回调
    public function scanback($data)
    {
        $merchant_no = isset($data['merchant_no'])?$data['merchant_no']:'';
        $out_trade_no = isset($data['out_trade_no'])?$data['out_trade_no']:'';
        $trans_status = isset($data['trans_status'])?$data['trans_status']:'';
        $trans_time = isset($data['trans_time'])?$data['trans_time']:'';
        $trans_oktime = isset($data['trans_oktime'])?$data['trans_oktime']:'';
        $total_fee = isset($data['total_fee'])?$data['total_fee']:'';
        $trans_type = isset($data['trans_type'])?$data['trans_type']:'';
        $openid = isset($data['openid'])?$data['openid']:'';
        $transaction_id = isset($data['transaction_id'])?$data['transaction_id']:'';
        $out_transaction_id = isset($data['out_transaction_id'])?$data['out_transaction_id']:'';

        $pay_type = $trans_type;
        $pay_price = $total_fee;
        $shop = Shop::get(['merchant_no'=>$merchant_no]);
        $shop_id = $shop?$shop->shop_id:0;
        if ($trans_type=='wxpay'){
            //微信
            $user = User::get(['wechat_open_id'=>$openid]);
            $user_id = $user?$user->id:0;
        } elseif ($trans_type=='alipay'){
            //支付宝

        } else {
            //云闪付

        }
        //商户账单
        $bills_model = new ShopBills();
        $res = $bills_model->add($user_id,$shop_id,$pay_price,$pay_type,strtotime($trans_oktime));
        return $res;
    }

    /**
     * 签名
     * @param array $data
     * @return array
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function signature(array $data)
    {
        $pre_data = [
            'data' => json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
            'agent_no' => $this->agent_no,
            'nonce' => self::getRandomStr(16),
            'timestamp' => time(),
            'version' => '1.0',
        ];
        $pre_data['signature'] = self::createSignature($pre_data);
        return $pre_data;
    }

    /**
     * 创建签名字符串
     * @param $data
     * @return string
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function createSignature($data)
    {
        // 1. 预签名数组 注意按照ascii排序
        ksort($data);
        // 2. 对数据进行k=v拼接并用&连接,内容为空的除外，例如：a=1&b=2
        $pre_str = '';
        foreach($data as $k => $v)
        {
            // 空值不参与签名
            !empty($v) && $pre_str .= $k . "=" . $v . "&";
        }
        // 3. 将auth_key拼接到最后边
        $pre_str .= 'secret_key='.$this->secret_key;
        // 4. 对数据进行md5加密，并转大写
        return strtoupper(md5($pre_str));
    }

    /**
     * 随机字符串
     * @param $len
     * @return string
     * @author cfn <cfn@leapy.cn>
     * @date 2021/11/9
     */
    protected function getRandomStr($len)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        mt_srand(10000000*(double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars)-1; $i < $len; $i++){
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }
}